package cn.shyouchi.wuguanjia.android.ui.event.arrange;


import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.chad.library.adapter.base.entity.MultiItemEntity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.event.EventApi;
import cn.shyouchi.wuguanjia.android.base.BaseFragment;
import cn.shyouchi.wuguanjia.android.event.AarrangeSelLineEvent;
import cn.shyouchi.wuguanjia.android.event.PersonRankEvent;
import cn.shyouchi.wuguanjia.android.event.SelPersonRankEvent;
import cn.shyouchi.wuguanjia.android.impl.ModuleItemClickListener;
import cn.shyouchi.wuguanjia.android.impl.OnItemClickListener;
import cn.shyouchi.wuguanjia.android.model.BaseRequestResult;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import cn.shyouchi.wuguanjia.android.ui.event.labor.LaborRequestEntity;
import cn.shyouchi.wuguanjia.android.ui.event.train.VirtualData;
import cn.shyouchi.wuguanjia.android.utils.LogUtil;
import cn.shyouchi.wuguanjia.android.utils.ToastUtil;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * A simple {@link Fragment} subclass.
 */
public class ArrangeFragment extends BaseFragment implements
        OnItemClickListener<LaborRequestEntity.ResultMessageBean.ServiceBeanX>,
        ModuleItemClickListener<PersonRankAdapter.Person> {


    @BindView(R.id.rv_rank)
    RecyclerView mRvRank;
    @BindView(R.id.btn_save)
    Button mBtnSave;
    @BindView(R.id.tv_date_title)
    TextView mTvTitle;

    boolean isSave = true;
    EventApi mEventApi;


    //    List<LaborRequestEntity.ResultMessageBean.ServiceBeanX> serviceBeanXes = new ArrayList<>();
    List<MultiItemEntity> serviceBeanXes = new ArrayList<>();

    RankAdapter mRankAdapter;

    String date;


    PersonRankAdapter.Person currentPerson;

    @Override
    public void initInjector() {
        mEventApi = new EventApi(getContext());
    }


    @Override
    public int initContentView() {

        return R.layout.fragment_arrange;
    }

    @Override
    public void getBundle(Bundle bundle) {

    }

    @Override
    public void initUI(View view) {
        ButterKnife.bind(this, view);
        showContent(true);
        mRankAdapter = new RankAdapter(serviceBeanXes, this, this);
        mRvRank.setAdapter(mRankAdapter);
        mRvRank.setLayoutManager(new LinearLayoutManager(getContext()));


    }

    @Override
    public void initData() {

    }

    public void refreshList() {
        mRankAdapter.notifyDataSetChanged();

        for (int i = 0; i < serviceBeanXes.size(); i++) {
            mRankAdapter.collapse(i, false, false);
        }

        for (int i = 0; i < serviceBeanXes.size(); i++) {
            mRankAdapter.expandAll(i, false, false);
        }
    }

    public void setRankData(LaborRequestEntity.ResultMessageBean entity) {
        isSave = true;
        date = entity.getDate();
        mTvTitle.setText(String.format("%1s班次及巡检线路安排", entity.getDate()));
        for (LaborRequestEntity.ResultMessageBean.ServiceBeanX c : entity.getService()) {
            c.setExpanded(false);
        }

        this.serviceBeanXes.clear();
        this.serviceBeanXes.addAll(entity.getService());
        refreshList();
    }

    @OnClick(R.id.btn_save)
    public void onClick() {
        saveDate();
    }

    @Override
    public void onItemClick(LaborRequestEntity.ResultMessageBean.ServiceBeanX entity) {
        Intent intent = new Intent(getContext(), AddArrangeActivity.class);
        intent.putExtra("id", entity.getService().getId());
        intent.putExtra("name", entity.getService().getServicesname());
        intent.putExtra("date", date);
        intent.putExtra("count", entity.getService_people());
        intent.putParcelableArrayListExtra("persons", (ArrayList<? extends Parcelable>) ((EventArrangeActivity) getActivity()).getPersonRankAdapters());
        intent.putParcelableArrayListExtra("selPersons", (ArrayList<? extends Parcelable>) getSelPersons());
        startActivity(intent);
    }




    private List<PersonRankAdapter.Person> getSelPersons() {
        List<PersonRankAdapter.Person> selPersons = new ArrayList<>();
        for (MultiItemEntity entity : serviceBeanXes) {
            if (entity instanceof LaborRequestEntity.ResultMessageBean.ServiceBeanX) {
                LaborRequestEntity.ResultMessageBean.ServiceBeanX item = (LaborRequestEntity.ResultMessageBean.ServiceBeanX) entity;
                if (item.getSubItems() != null) {
                    selPersons.addAll(item.getSubItems());
                }
            }
        }
        return selPersons;
    }


    @Override
    public void onDel(PersonRankAdapter.Person person) {
        isSave = false;
        EventBus.getDefault().post(new PersonRankEvent(person, ((LaborRequestEntity.ResultMessageBean.ServiceBeanX) person.getTag()).getService().getId(), PersonRankEvent.CHANGE_TYPE_ADD));
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSelFinish(SelPersonRankEvent event) {
        isSave = false;
        LaborRequestEntity.ResultMessageBean.ServiceBeanX serviceBeanX = mRankAdapter.getServiceByRankId(event.getRank_id());
        if (serviceBeanX != null) {
            for (PersonRankAdapter.Person person : event.getPersons()) {
                person.setTag(serviceBeanX);
                serviceBeanX.addSubItem(person);
                EventBus.getDefault().post(new PersonRankEvent(person, serviceBeanX.getService().getId(), PersonRankEvent.CHANGE_TYPE_SUB));
            }
        }
        refreshList();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void saveDate() {
        VirtualData virtualData = new VirtualData();
        virtualData.setDate(date);
        List<VirtualData.Rank> ranks = new ArrayList<>();
        for (MultiItemEntity entity : mRankAdapter.getData()) {
            if (entity instanceof LaborRequestEntity.ResultMessageBean.ServiceBeanX) {
                LaborRequestEntity.ResultMessageBean.ServiceBeanX s = ((LaborRequestEntity.ResultMessageBean.ServiceBeanX) entity);
                VirtualData.Rank rank = new VirtualData.Rank(s.getService().getId(), s.getService().getServicesname());
                List<VirtualData.User> users = new ArrayList<>();
                if (s.getSubItems() != null) {
                    for (PersonRankAdapter.Person p : s.getSubItems()) {
                        users.add(new VirtualData.User(p.getUser_id(), p.getUser_name(), p.getLine() != null ? p.getLine().getId() : 0));
                    }
                }
                rank.setUsers(users);
                ranks.add(rank);
            }
        }
        virtualData.setRanks(ranks);
        LogUtil.json(virtualData);
        mEventApi.schedulingAdd(((EventArrangeActivity) getActivity()).getProjectId(), virtualData)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<BaseRequestResult>(getContext()) {
                    @Override
                    public void onNext(BaseRequestResult result) {
                        isSave = true;
                        ToastUtil.showToast("数据保存成功");
                    }
                });
    }


    @Override
    public void moduleItemClick(PersonRankAdapter.Person model) {
        currentPerson = model;
        Intent intent = new Intent(getContext(), ArrangeSelLineActivity.class);
        intent.putExtra("projectId", ((EventArrangeActivity) getActivity()).getProjectId());
        getContext().startActivity(intent);
    }

    @Override
    public void moduleItemLongClick(PersonRankAdapter.Person model) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onArrangeSelLine(AarrangeSelLineEvent event) {
        if (currentPerson != null) {
            isSave = false;
            currentPerson.setLine(event.getLine());
            mRankAdapter.notifyDataSetChanged();
        }
    }


}
